<template>
    <!--物资验收修改 -->
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="验收明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="serviceCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="验收编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="所属机构">
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="业务类型"
                                                    prop="businessType"
                                                >
                                                    <el-select
                                                        v-model="
                                                            formData.businessType
                                                        "
                                                        placeholder="请选择"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                        @change="
                                                            businessTypeChange
                                                        "
                                                    >
                                                        <el-option
                                                            v-for="item in businessTypeList"
                                                            :key="item.value"
                                                            :label="item.key"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                    <span v-else>{{
                                                        businessType
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="源单编号">
                                                    <!--  v-if="
                                                            formData.redBillState !=
                                                            '3'
                                                        " -->
                                                    <el-input
                                                        v-model="
                                                            formData.sourceBillNo
                                                        "
                                                        readonly
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                sourceBillNoClick
                                                            "
                                                            v-show="
                                                                formData.sourceBillId
                                                            "
                                                        ></i>
                                                    </el-input>
                                                    <span v-else>
                                                        {{
                                                            formData.sourceBillNo
                                                        }}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                sourceBillNoClick
                                                            "
                                                            v-if="
                                                                formData.sourceBillNo
                                                            "
                                                        ></i>
                                                    </span>
                                                    <!-- <span v-else>{{
                                                        formData.sourceBillNo
                                                    }}</span> -->
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商"
                                                    prop="supplierName"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.supplierName
                                                        "
                                                        readonly
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                supplierNameClick
                                                            "
                                                        ></i>
                                                    </el-input>
                                                    <span v-else>{{
                                                        formData.supplierName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="采购人员"
                                                    prop="purchaserName"
                                                >
                                                    {{ formData.purchaserName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(元)"
                                                    prop="acceptanceAmount"
                                                >
                                                    {{
                                                        formData.acceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="验收人员">
                                                    <el-input
                                                        v-model="
                                                            formData.acceptancerName
                                                        "
                                                        readonly
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                acceptancerNameClick
                                                            "
                                                        ></i>
                                                    </el-input>
                                                    <span v-else>{{
                                                        formData.acceptancerName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期"
                                                    prop="acceptanceDate"
                                                >
                                                    <el-date-picker
                                                        v-model="
                                                            formData.acceptanceDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                    </el-date-picker>
                                                    <span v-else>{{
                                                        formData.acceptanceDate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="服务费用(元)"
                                                    prop="freight"
                                                >
                                                    {{ formData.freight }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.taxRate
                                                        "
                                                        @input.native="
                                                            onInput0_100
                                                        "
                                                        v-enter-float="{
                                                            set: formData,
                                                            key: 'taxRate'
                                                        }"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.taxRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.taxAmount
                                                        "
                                                        v-enter-float="{
                                                            set: formData,
                                                            key: 'taxAmount'
                                                        }"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.taxAmount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税价合计"
                                                    prop="totalAmount"
                                                >
                                                    {{ formData.totalAmount }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                    <el-select
                                                        v-model="
                                                            formData.currencyId
                                                        "
                                                        placeholder="请选择"
                                                        v-if="
                                                            (formData.businessType ===
                                                                0 ||
                                                                formData.businessType ===
                                                                    3) &&
                                                            formData.redBillState !=
                                                                3
                                                        "
                                                        @change="currencyChange"
                                                    >
                                                        <el-option
                                                            v-for="item in currencyForm"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                    <span v-else>{{
                                                        formData.currency
                                                    }}</span>
                                                    <!-- v-if="
                                                            formData.businessType ==
                                                            3
                                                        " -->
                                                    <!-- <span v-else>{{
                                                        formData.currency
                                                    }}</span> -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.baseCurRate
                                                        "
                                                        v-enter-float2="{
                                                            set: formData,
                                                            key: 'baseCurRate'
                                                        }"
                                                        v-if="
                                                            !isBaseCurRate &&
                                                            formData.redBillState !=
                                                                3
                                                        "
                                                        @blur="baseCurRateBlur"
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.baseCurRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                                <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    resize="none"
                                                    placeholder="请输入内容"
                                                    v-model="formData.remarks"
                                                    maxlength='500'
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                    <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col
                                                :span="12"
                                                v-if="
                                                    formData.redBillState !==
                                                    -1
                                                "
                                            >
                                                <el-form-item label="冲红单">
                                                    <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 验收明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            验收明细
                        </div>
                        <div class="e-table">
                            <div class="top" v-if="formData.redBillState != 3">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="supplierNameClick"
                                            >选择收料</el-button
                                        >
                                        <el-button
                                            size="mini"
                                            class="btn-delete"
                                            @click="acceptanceDeleteClick"
                                            >批量删除</el-button
                                        >
                                    </div>
                                    <!-- <div
                                        class="batchBox"
                                        @click="batchOperation('acceptance')"
                                    >
                                        <img
                                            class="batchicon"
                                            src="@/assets/piliang.png"
                                        />
                                        <span class="batchfont">{{
                                            isBatch[0].batch
                                        }}</span>
                                    </div> -->
                                </div>
                            </div>
                            <div
                                class="errorMsg"
                                v-if="errorAcceptanceMsg.length > 0"
                            >
                                <span>
                                    {{ errorAcceptanceMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="acceptanceData"
                                border
                                style="width: 100%"
                                ref="acceptanceTable"
                                :row-class-name="tableRowClassName"
                                @select='selectRow'
                                @selection-change="acceptanceSelect"
                                @select-all='acceptanceSelectAll'
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                :class='tableHeadClass'
                                v-sortTable="{ 'tableData': acceptanceData, '_this': this, 'ref': 'acceptanceTable' }"
                            >
                                <el-table-column type="selection" width="55" v-if='formData.redBillState != 3'>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    fixed
                                    align="center"
                                    v-if="formData.redBillState != 3"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div
                                            class="handle"
                                            v-if="!row.children"
                                        >
                                            <div
                                                style="cursor: pointer"
                                                class="list_box"
                                            >
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    class="add_sub"
                                                    title="删除"
                                                    @click="
                                                        acceptanceDelete(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    min-width="170"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="notAcceptedQuantity"
                                    label="未验收数量"
                                    width="100"
                                >
                                    <template v-slot="{ row }">
                                        <span v-if="!row.children">{{
                                            +(+row.notAcceptedQuantity -
                                            +row.acceptanceQuantity).toFixed(4)
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="验收数量" width="120">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.acceptanceQuantity"
                                            v-enter-float2="{
                                                set: row,
                                                key: 'acceptanceQuantity'
                                            }"
                                            placeholder=""
                                            @blur="acceptanceQuantityBlur(row)"
                                            v-if="
                                                !row.children &&
                                                formData.redBillState != 3
                                            "
                                        ></el-input>
                                        <span v-else>{{
                                            row.acceptanceQuantity
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="验收单价（元）"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="验收金额（元）"
                                    width="120"
                                >
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.acceptanceAmount"
                                            v-enter-float="{
                                                set: row,
                                                key: 'acceptanceAmount'
                                            }"
                                            placeholder=""
                                            @blur="acceptanceAmountBlur(row)"
                                            v-if="
                                                !row.children &&
                                                formData.redBillState != 3
                                            "
                                        ></el-input>
                                        <span v-else>{{
                                            row.acceptanceAmount
                                        }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="serviceChargeCon" class="con">
                        <div class="tabs-title" id="serviceCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <div
                                class="top"
                                v-if="
                                    formData.redBillState != 3 && isServiceFee
                                "
                            >
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="serviceFeeAdd"
                                            >新增行</el-button
                                        >
                                        <el-button
                                            size="mini"
                                            class="btn-delete"
                                            @click="serviceFeeDeleteClick"
                                            >批量删除</el-button
                                        >
                                    </div>
                                    <!-- <div
                                        class="batchBox"
                                        @click="batchOperation('serviceFee')"
                                    >
                                        <img
                                            class="batchicon"
                                            src="@/assets/piliang.png"
                                        />
                                        <span class="batchfont">{{
                                            isBatch[1].batch
                                        }}</span>
                                    </div> -->
                                </div>
                            </div>
                            <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="serviceFeeData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassNameF"
                                @selection-change="serviceFeeSelect"
                                ref="serviceFeeTable"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTable' }"
                            >
                                <el-table-column type="selection" width="55" v-if='formData.redBillState != 3'>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="formData.redBillState != 3"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div
                                                style="cursor: pointer"
                                                class="list_box"
                                            >
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    class="add_sub"
                                                    title="删除"
                                                    @click="
                                                        serviceFeeDelete(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="合同编号"
                                    fixed
                                    min-width="150"
                                >
                                    <template v-slot="{ row, $index }">
                                        {{ row.contractBillNo }}
                                        <i
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                            "
                                            class="el-icon-document-copy"
                                            @click="contractDialog(row, $index)"
                                            v-if="formData.redBillState != 3"
                                        ></i>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    min-width="190"
                                >
                                    <template v-slot="{ row, $index }">
                                        {{ row.settlementUnitName }}
                                        <i
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                            "
                                            class="el-icon-document-copy"
                                            @click="
                                                billingUnitDialog(row, $index)
                                            "
                                            v-if="formData.redBillState != 3"
                                        ></i>
                                    </template>
                                </el-table-column>
                                <el-table-column label="清单名称" width="100">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.contractDtlName"
                                            placeholder=""
                                            v-if="
                                                formData.redBillState != 3 &&
                                                !row.contractBillNo
                                            "
                                            @blur="contractDtlNameBlur"
                                        ></el-input>
                                        <span v-else>{{
                                            row.contractDtlName
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" width="100">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.quantity"
                                            v-enter-float2="{
                                                set: row,
                                                key: 'quantity'
                                            }"
                                            placeholder=""
                                            @blur="quantityBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.quantity }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column label="金额(元)" width="100">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.amount"
                                            v-enter-float="{
                                                set: row,
                                                key: 'amount'
                                            }"
                                            placeholder=""
                                            @blur="amountBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.amount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="发票编号" width="130">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.invoiceNo"
                                            v-enterInteger1
                                            placeholder=""
                                            @blur="invoiceNoBlur(row)"
                                            v-if="
                                                formData.redBillState != 3
                                            "
                                        ></el-input>
                                        <span v-else>{{ row.invoiceNo }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="税率%" width="130">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.taxRate"
                                            v-enter-float="{
                                                set: row,
                                                key: 'taxRate'
                                            }"
                                            @input.native="onInput0_100"
                                            placeholder=""
                                            @blur="taxRateBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.taxRate }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="税额（元）" width="130">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.taxAmount"
                                            v-enter-float="{
                                                set: row,
                                                key: 'taxAmount'
                                            }"
                                            placeholder=""
                                            @blur="taxAmountBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.taxAmount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计（元）"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            :isView='formData.redBillState != 3 ? false : true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="1017"
                            :billId="billid"
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 1 || formData.state == 9"
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 2 && formData.redBillState == -1"
                >冲红单</el-button
            >
            <exaButtons
                :auditState="auditState"
                @exas="exas"
                :state="formData.state"
                :founderId="formData.founderId"
            ></exaButtons>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showLoading, hideLoading, openAppClient } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/materials/materialAcceptance'
import priceRequest from '@/api/materials/priceAcceptance'
import { getUuid } from '@/utils/common'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'
import exaButtons from '@/components/common/exaButtons'

export default {
    components: {
        AttachComp,
        AcceptanceHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            acceptanceData: [], // 验收明细数据
            serviceFeeData: [], //服务费用数据
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                acceptanceAmount: '',
                acceptanceDate: '',
                acceptanceQuantity: 0,
                acceptancerId: '',
                acceptancerName: '',
                baseCurAcceptanceAmount: 0,
                baseCurFreight: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                billNo: '',
                businessType: 0,
                currency: '',
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                freight: 0,
                gmtCreate: '',
                gmtModified: '',
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                purchaserId: '',
                purchaserName: '',
                purchasingUnitId: '',
                purchasingUnitName: '',
                redBillId: '',
                redBillNo: '',
                redBillState: 0,
                remarks: '',
                rmbAcceptanceAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                showEas: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                supplierId: '',
                supplierName: '',
                taxAmount: '',
                taxRate: '',
                totalAmount: '',
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转,
            businessTypeList: [
                {
                    value: 0,
                    key: '零星采购计划'
                },
                {
                    value: 1,
                    key: '物资采购合同'
                },
                {
                    value: 2,
                    key: '调入（调拨单）'
                }
            ],
            formDataRules: {
                businessType: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                supplierName: [
                    { required: true, message: '请选择供应商', trigger: 'blur' }
                ],
                purchaserName: [
                    {
                        required: true,
                        message: '请选择采购人员',
                        trigger: 'blur'
                    }
                ],
                acceptanceAmount: [
                    {
                        required: true,
                        message: '请输入验收金额',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                totalAmount: [
                    {
                        required: true,
                        message: '请输入税价合计',
                        trigger: 'blur'
                    }
                ],
                freight: [
                    {
                        required: true,
                        message: '请输入服务费用',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ]
            },
            MouseEnterId: null,
            MouseEnterIdF: null,
            serviceFeeRow: {
                amount: null,
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: null,
                quantity: null,
                settlementUnitId: '',
                settlementUnitName: '',
                taxAmount: null,
                taxRate: null,
                totalAmount: null
            },
            billingUnitQuery: {
                businessUnitTypes: [],
                keyword: '',
                limit: 2,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: []
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: '1017',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1017',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorAcceptanceMsg: [], // 验收明细
            errorServiceFeeMsg: [], // 服务费用
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            redFormData: null,
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: [0, 1, 2],
                supplierTypes: [],
                subcontractorTypes: [],
                businessTypes: []
            },
            jsdwIds: null,
            isBaseCurRate: true,
            isSubmit: false,
            acceptanceList: [], // 验收已选数据
            serviceFeeList: [], // 服务费用已选数据
            acceptanceDelData: [],
            isServiceFee: false,
            acceptanceSelects: false,
            selectFlag: false,
            tableHeadClass: 'cancelClass',
            businessType: ''
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },

        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 100 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        // 监听验收明细的子级是否有数据, 如果没有数据,则服务费用处不显示新增和删除按钮
        acceptanceData: {
            handler: function () {
                if (this.acceptanceData.length < 1) {
                    this.isServiceFee = false
                    this.formData.sourceBillId = ''
                } else {
                // 如果每一个子项的changeType都为 -1  就说明都删除了, 那服务费用就不能显示 新增/删除按钮
                    let arr = []
                    this.acceptanceData.forEach(item => {
                        let isData = item.children.every(
                            its => its.changeType === -1
                        )
                        arr.push(isData)
                    })
                    let isSubmit = arr.every(i => i === true)
                    if(isSubmit) {
                        this.isServiceFee = false
                        this.formData.sourceBillId = ''
                        this.acceptanceSelects = false
                    }else {
                        this.isServiceFee = true
                    }
                }
            },
            deep: true
        },
        // 监听验收明细的子级是否有数据, 如果验收明细删除至没有数据,那么服务费用中如果有数据则需要删除服务费用中的数据
        isServiceFee () {
            if(!this.isServiceFee) {
                for(let i = 0; i < this.serviceFeeData.length; i++) {
                    if(this.serviceFeeData[i]['dtlId']) {
                        this.$set(this.serviceFeeData[i], 'changeType', -1)
                        this.$set(this.serviceFeeData[i], 'amount', 0)
                        this.$set(this.serviceFeeData[i], 'totalAmount', 0)
                    }else{
                        this.serviceFeeData.splice(i, 1)
                        i--
                    }
                }
            }
        },
        'acceptanceSelects' () {
            if(this.acceptanceSelects) {
                this.tableHeadClass = 'tableHeadClass'
            } else {
                this.tableHeadClass = 'cancelClass'
            }
            console.log(this.acceptanceSelects)
        },
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.getAllData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'receivingMaterials',
            'serviceCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })

            console.log($idsTop)
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicData(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicData () {
            let data = await priceRequest.getBasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            if (data.redBillState == '3') {
                // 如果是3,说明进入该单据是红单进入到编辑页
                this.businessType = this.businessTypeList.find(
                    item => item.value === data.businessType
                ).key
                data.currency = this.currencyForm.find(
                    x => x.value == data.currencyId
                ).label
                this.formData = data
            } else {
                this.formData = data
            }

            // 开启验收金额(元)的监听
            this.$watch('formData.acceptanceAmount', () => {
                // 税额 = 不含税金额 * 税率
                this.formData.taxAmount = +(
                    +this.formData.acceptanceAmount *
                    +(+this.formData.taxRate / 100)
                ).toFixed(2)
                // 税价合计 = 验收金额 + 税额
                this.formData.totalAmount =
                    // +this.formData.acceptanceAmount +
                    // +this.formData.taxAmount
                    +(
                        (+this.formData.acceptanceAmount * 100 +
                            +this.formData.taxAmount * 100) /
                        100
                    ).toFixed(2)
                // 验收金额(本位币) = 验收金额 * 本位币汇率
                this.formData.baseCurAcceptanceAmount = +(
                    +this.formData.acceptanceAmount * +this.formData.baseCurRate
                ).toFixed(2)
                // // 计算验收明细中每一条明细的税额, 可在保存时,再计算
                // this.acceptanceData.forEach(item => {
                //     item.children.forEach(it => {
                //         it.taxAmount = +(+it.acceptanceAmount * +(+this.formData.taxRate / 100)).toFixed(2)
                //     })
                // })
            })
            // 监听税率, 税额 = 不含税金额 * 税率
            this.$watch('formData.taxRate', () => {
                this.formData.taxAmount = +(
                    +this.formData.acceptanceAmount *
                    +(+this.formData.taxRate / 100)
                ).toFixed(2)
                // // 计算验收明细中每一条明细的税额
                // this.acceptanceData.forEach(item => {
                //     item.children.forEach(it => {
                //         it.taxAmount = +(+it.acceptanceAmount * +(+this.formData.taxRate / 100)).toFixed(2)
                //     })
                // })
            })
            // 监听税额
            this.$watch('formData.taxAmount', () => {
                // 税价合计 = 验收金额+税额
                this.formData.totalAmount = +(
                    (+this.formData.acceptanceAmount * 100 +
                        +this.formData.taxAmount * 100) /
                    100
                ).toFixed(2)
            })
            // 监听服务费用税价合计
            this.$watch('serviceFeeData', () => {
                this.formData.freight = +(this.serviceFeeData.reduce((prev, c) => prev += (+c.totalAmount || 0), 0)).toFixed(2)
            }, { deep: true })

            await this.getAcceptanceList() // 验收明细表格数据
            await this.getServeList() // 服务费用表格数据
        },

        // 源单编号-跳转到现场收料的详情页
        sourceBillNoClick () {
            let url = ''
            let name = ''
            switch (this.formData.businessType) {
            case 0:
                url = '/sporadicPurchaseParticulars'
                name = '查看零星采购计划'
                break
            case 1:
                url = '/ctMaterialApplyShow'
                name = '查看物资采购合同'
                break
            case 2:
                url = '/revolveAllocationShow'
                name = '查看调入(调拨单)'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceBillId}&isview=${true}`,
                `${name}`
            )
        },
        // 选择验收人员
        async acceptancerNameClick () {
            let data = await request.getAcceptancerName()
            this.formData.acceptancerId = data.userId
            this.formData.acceptancerName = data.userName
        },

        // 供应商处: 选择收料明细,选择收料明细和验收明细处的选择收料处理逻辑是一致的
        async supplierNameClick () {
            if (this.formData.businessType === '') {
                return this.clientPop('err', '请先选择业务类型')
            }
            // this.setSelectedInfo(this.acceptanceData)
            // openAppClient('/showSelectedData', '数组')
            let dtlIds = []
            this.acceptanceData.forEach(item => {
                let dtlId = []
                item.children.forEach(it => {
                    if (it.changeType !== -1) {
                        dtlId.push(it.sourceDtlId)
                    }
                })
                dtlIds.push(...dtlId)
            })
            try {
                let res = await priceRequest.getSourceList(
                    {
                        businessType: this.formData.businessType,
                        parentId: 0
                    },
                    dtlIds
                )
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                //如果点击确定时，未选择数据，即数组是空的
                if (res.length < 1) {
                    this.clientPop('err', '请选择验收明细！')
                    // this.businessTypeChange()
                    return
                }
                // 先判断所选择的数据是否都是同一个合同下的,如果不是同一个合同直接提示并且不执行后面操作
                let isSameContract = res.some(item => res[0].sourceId !== item.sourceId)
                if(isSameContract) {
                    this.clientPop('err', '只能选择同一个合同下的数据进行验收,请重新选择!')
                    return
                }
                let data = res.find(item => item.parentId != 0)

                // 不能选择不同的合同
                // if(this.formData.sourceBillId && (this.formData.sourceBillId !== data.sourceId)) {
                //     this.clientPop('err', '只能选择同一个合同下的数据进行验收,请重新选择!')
                //     return
                // }
                // val是关闭弹窗后,返回的数据
                if (!res) {
                    return
                } else {
                    // if (!Array.isArray(res)) return
                    // 如果还没有供应商的情况,选择数据后直接赋值
                    if (
                        this.acceptanceData.length < 1 ||
                        !this.formData.supplierId
                    ) {
                        this.assignmentFun(data)
                        this.acceptanceData = this.acceptanceFun(res)
                    } else if (this.formData.sourceBillNo != data.sourceNumber) {
                        // 如果原有供应商和当前选择供应商不一致
                        this.clientPop(
                            'info',
                            '当前选择源单与原有源单不同,若点击确定,原有基本信息和结算明细将被覆盖!',
                            () => {
                                // 如果点击的确认,则处理数据格式,并把最新的数据赋值给验收明细数组
                                this.jgdwChange()
                                this.assignmentFun(data)
                                this.acceptancePush(res)
                                this.subtotalFn()
                            }
                        )
                    } else {
                        this.acceptancePush(res)
                        this.subtotalFn()
                    }

                }
                // this.clientPop('info', 'datas', JSON.stringify(this.acceptanceData))
            } catch (err) {
                alert(err.message)
            }
        },
        // 处理弹窗获取回来的数据格式
        acceptanceFun (res) {
            const newArr = []
            let obj = {}
            res.forEach(item => {
                if (item.materialClassName) {
                    const topClassName = item.materialClassName.split('/')[0]
                    const topClassId = item.materialClassId.split('/')[0]
                    obj = {
                        topClassId,
                        topClassName,
                        customId: topClassId,
                        materialClassId: topClassId,
                        materialClassName: topClassName,
                        uuid: getUuid(),
                        totalAmount: null,
                        totalQuantity: null,
                        children: [],
                        isChecked: false,
                    }
                    if (newArr.length < 1) {
                        newArr.push(obj)
                    } else {
                        let isParent = newArr.every(
                            itm => itm.topClassId !== topClassId
                        )
                        if (isParent) {
                            newArr.push(obj)
                        }
                    }

                    newArr.forEach(its => {
                        if(its.materialClassId === item.materialClassId.split('/')[0]) {
                            its.children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                acceptanceQuantity: item.acceptedQuantity, //已验收数量
                                billId: this.billid, //	验收ID
                                changeType: 1, //变更类型
                                dtlId: '', //验收明细ID
                                materialClassId: item.materialClassId
                                    .split('/')
                                    .slice(1)
                                    .join('/'), //物资类别id
                                materialClassName: item.materialClassName
                                    .split('/')
                                    .slice(1)
                                    .join('/'), // 物资类别名称
                                materialId: item.materialId, //物资id
                                materialName: item.materialName, //物资名称
                                notAcceptedQuantity: item.acceptedQuantity, // 未验收数量
                                sourceAdjustmentAcceptanceDtlId: '',
                                sourceDtlId: item.dtlId, //源单明细id
                                spec: item.spec, //规格型号
                                taxAmount: 0, // 税额
                                texture: item.texture, //材质
                                unit: item.unit, //计量单位
                                warehouseId: item.warehouseId, //仓库id
                                warehouseName: item.warehouseName,
                                acceptanceAmount: '',
                                price: '',
                                settledQuantity: 0,
                                parentId: its.topClassId, // 前端自存字段,不需要传到后端的,作用是需要一个和父级相关联的id,在全选时方便找到对应父级
                            })
                        }
                        // 统计小计
                        const count = +(its.children
                            .reduce(
                                (prev, c) => (prev += +c.acceptanceAmount || 0),
                                0
                            ))
                            .toFixed(2)
                        its.materialName = `金额小计： ${count}`
                    })
                }
            })
            return newArr
        },
        async assignmentFun (data) {
            this.formData.supplierName = data.supplierName // 供应商
            this.formData.supplierId = data.supplierId // 供应商ID
            this.formData.purchaserName = data.purchasingPersonnelName // 采购人员名称
            this.formData.purchaserId = data.purchasingPersonnelId // 采购人员ID
            this.formData.sourceBillNo = data.sourceNumber // 源单编号
            this.formData.sourceBillId = data.sourceId // 源单ID

            // 如果选择的是调拨单,需要调接口(吉吉的接口)获取币种,本位币,如果是物资采购合同：还需要带入合同税率
            if (this.formData.businessType === 2) {
                try {
                    let res1 = await request.getCurrency(data.sourceId)
                    // this.setSelectedInfo(res1)
                    // openAppClient('/showSelectedData', '选择结果')
                    if (!res1.code) {
                        this.formData.currency = res1.currency // 币种名称
                        this.formData.currencyId = res1.currencyId // 币种ID
                        // this.formData.baseCurName = res1.baseCurName // 本位币名称
                        // this.formData.baseCurId = res1.baseCurId // 本位币ID
                    } else {
                        this.formData.currency = ''
                        this.formData.currencyId = ''
                    }
                } catch (err) {
                    this.formData.currency = ''
                    this.formData.currencyId = ''
                }
            }
            // // 如果选择的是物资采购合同,调合同的接口(胡腾的接口)带入税率
            if (this.formData.businessType === 1) {
                try {
                    // this.setSelectedInfo(data.sourceId)
                    // openAppClient('/showSelectedData', '传参')
                    let data1 = await request.getcontractbasicInfo(
                        data.sourceId
                    )
                    // this.setSelectedInfo(data1)
                    // openAppClient('/showSelectedData', '选择结果')
                    if (!data1.code) {
                        this.formData.currency = data1.currencyName // 币种名称
                        this.formData.currencyId = data1.currencyId // 币种ID
                        // this.formData.baseCurName = data1.baseCurName // 本位币名称
                        // this.formData.baseCurId = data1.baseCurId // 本位币ID
                        this.formData.taxRate = data1.taxRate // 物资采购合同：带入合同税率。
                    } else {
                        this.formData.currency = ''
                        this.formData.currencyId = ''
                        this.formData.taxRate = 0
                    }
                } catch (err) {
                    this.formData.currency = ''
                    this.formData.currencyId = ''
                    this.formData.taxRate = 0
                }
            }
            // 业务类型为零星采购计划时带出税率
            if (this.formData.businessType === 0) {
                try{
                    let taxRate = await request.getTaxRate(data.sourceId)
                    // this.setSelectedInfo(taxRate)
                    // openAppClient('/showSelectedData', '选择结果')
                    if (!taxRate.code) {
                        this.formData.taxRate = taxRate
                    }else {
                        this.formData.taxRate = ''
                    }
                }catch(err) {
                    this.formData.taxRate = ''
                }
            }
        },
        acceptancePush (res) {
            let newArr = this.acceptanceFun(res)
            newArr.forEach(item => {
                const topClassIdRp = this.acceptanceData.every(
                    itm => itm.topClassId != item.topClassId
                )
                // 遍历当前选择数据的每一项父级id是否存在于原有数组中,如果没有,则直接添加
                if (topClassIdRp) {
                    this.acceptanceData.push(item)
                } else {
                    // 如果数组中的父级id一样,则返回一样的那一项的父级数据
                    const target = this.acceptanceData.find(
                        its => its.topClassId == item.topClassId
                    )
                    // 给这条父级数据的children里面添加子级
                    item.children.forEach(it => {
                        // 如果当前父级的子级中没有相同的,则直接添加
                        const materialIdRp = target.children.every(
                            _it => (_it.materialId != it.materialId) || (_it.spec != it.spec) || (_it.texture != it.texture) || (_it.unit != it.unit) || (_it.warehouseId != it.warehouseId)
                        )
                        if (materialIdRp) {
                            target.children.push(it)
                        } else {
                            // 遍历出所有子级id一样的
                            const _target = target.children.filter(
                                i => (i.materialId == it.materialId) || (i.spec == it.spec) || (i.texture == it.texture) || (i.unit == it.unit) || (i.warehouseId == it.warehouseId)
                            )
                            // 如果当前遍历的子项存在于原数组,但是changeTpye等于-1说明已经删除,那还是可以重新添加进入的,changeType不等于-1的,不做操作;如果遍历完了都是等于-1的,才添加
                            const noPush = _target.some(
                                _i => _i.changeType !== -1
                            )
                            if (!noPush) {
                                target.children.push(it)
                            }
                        }
                    })
                }
            })
        },
        subtotalFn () {
            let count = 0
            let countSum = 0
            this.acceptanceData.forEach(item => {
                count = +(item.children
                    .reduce(
                        (pre, c) => (pre += +c.acceptanceAmount || 0),
                        0
                    ))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +countSum
            })
            this.formData.acceptanceAmount = +countSum.toFixed(2)
        },

        // 如果业务类型变化,需清除带入的数据
        businessTypeChange () {
            this.formData.supplierName = ''
            this.formData.supplierId = ''
            this.formData.purchaserName = ''
            this.formData.purchaserId = ''
            this.formData.sourceBillNo = ''
            this.formData.sourceBillId = ''
            this.formData.currency = ''
            this.formData.currencyId = ''
            // this.formData.baseCurName = ''
            // this.formData.baseCurId = ''
            this.formData.taxRate = ''
            this.formData.acceptanceAmount = ''
            this.jgdwChange()
        },
        jgdwChange () {
            // 当业务类型变化了或者供应商变了,需要处理验收明细的数据,不含税金额,税额等都需重新计算
            for (let i = 0; i < this.acceptanceData.length; i++) {
                for (
                    let m = 0;
                    m < this.acceptanceData[i]['children'].length;
                    m++
                ) {
                    if (this.acceptanceData[i]['children'][m]['dtlId']) {
                        this.$set(
                            this.acceptanceData[i]['children'][m],
                            'changeType',
                            -1
                        )
                        this.$set(
                            this.acceptanceData[i]['children'][m],
                            'acceptanceAmount',
                            0
                        )
                    } else {
                        this.acceptanceData[i]['children'].splice(m, 1)
                        m--
                    }
                }
            }
            this.formData.acceptanceAmount = 0
            // 需要把删除数据后的验收明细数据给一个空数组存起来,最后在保存时拼接上一并传给后端
            this.acceptanceDelData.push(...this.acceptanceData)
            // 服务费用也需要清空
            for (let i = 0; i < this.serviceFeeData.length; i++) {
                if (this.serviceFeeData[i]['dtlId']) {
                    this.$set(
                        this.serviceFeeData[i],
                        'changeType',
                        -1
                    )
                    this.$set(
                        this.serviceFeeData[i],
                        'totalAmount',
                        0
                    )
                    this.$set(
                        this.serviceFeeData[i],
                        'amount',
                        0
                    )
                } else {
                    this.serviceFeeData.splice(i, 1)
                    i--
                }
            }
            this.formData.freight = 0
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        // 本位币汇率失去焦点时
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            this.formData.baseCurAcceptanceAmount =
                +this.formData.acceptanceAmount * +this.formData.baseCurRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },

        // ------------------------------验收明细---------------------------------------

        // 获取验收明细表格数据(弹窗好了过后最终需要调的接口)
        async getAcceptanceList () {
            let res = await priceRequest.getAcceptanceList(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.isChecked = false
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                    i.parentId = item.topClassId
                })
                const count = +(item.children
                    .reduce((prev, c) => (prev += c.acceptanceAmount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.acceptanceData = res
        },

        // 监听验收数量
        acceptanceQuantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (
                +row.notAcceptedQuantity &&
                +row.acceptanceQuantity > +row.notAcceptedQuantity
            ) {
                this.clientPop(
                    'err',
                    `不能大于未验收数量${row.notAcceptedQuantity}`
                )
                row.acceptanceQuantity = row.notAcceptedQuantity
                if (+row.acceptanceAmount && +row.acceptanceQuantity) {
                    row.price = +(
                        +row.acceptanceAmount / +row.acceptanceQuantity
                    ).toFixed(2)
                }else{
                    row.price = 0
                }
            } else {
                if (!!row.acceptanceAmount && !!row.acceptanceQuantity) {
                    row.price = +(
                        +row.acceptanceAmount / +row.acceptanceQuantity
                    ).toFixed(2)
                } else {
                    row.price = 0
                }
            }
        },

        // 监听验收金额
        acceptanceAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.acceptanceQuantity) {
                row.price = +(
                    +row.acceptanceAmount / +row.acceptanceQuantity
                ).toFixed(2)
            }
            // 计算基本信息的验收金额
            let count = 0
            let countSum = 0
            this.acceptanceData.forEach(item => {
                count = +(item.children
                    .reduce((prev, c) => (prev += +c.acceptanceAmount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.formData.acceptanceAmount = +countSum.toFixed(2)
        },

        //删除验收明细
        acceptanceDelete (row) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.dtlId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.acceptanceData.forEach(item => {
                        item.children.forEach((its, index) => {
                            if (this._.isEqual(its, row)) {
                                item.children.splice(index, 1)
                            }
                        })
                    })
                }
                row.acceptanceAmount = 0
                let count = 0
                let countSum = 0
                this.acceptanceData.forEach(item => {
                    count = +(item.children
                        .reduce(
                            (pre, c) => (pre += +c.acceptanceAmount || 0),
                            0
                        ))
                        .toFixed(2)
                    item.materialName = `金额小计： ${count}`
                    countSum += +count
                })
                this.formData.acceptanceAmount = +countSum.toFixed(2)
            })
        },
        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            if(row.children) {
                if(row.children.length < 1) {
                    return 'warning-row'
                }else {
                    let isDel = row.children.every(it => it.changeType === -1)
                    if(isDel) {
                        return 'warning-row'
                    }
                }
            }
            return ''
        },
        // 全选
        acceptanceSelectAll (selection) {
            this.acceptanceSelects = !this.acceptanceSelects

            this.splite(this.acceptanceData, this.acceptanceSelects)

            // 如果点击全选后,选中数据的长度和原始数组中父级加上changeType不等于-1的子级数据总数相等,就说明是全选选中,否则是全不选中
            let count = 0
            this.acceptanceData.forEach(item => {
                count++
                item.children.forEach(it => {
                    if(it.changeType !== -1) {
                        count++
                    }
                })
            })
            // console.log(count)
            let num = 0
            selection.forEach(item => {
                if(item.changeType) {
                    if(item.changeType !== -1) {
                        num++
                    }
                }else {
                    num++
                }
            })
            // console.log(selection)
            if(num === count) {
                this.acceptanceSelects = true
            }else {
                this.acceptanceSelects = false
            }

            // 如果全选按钮是选中状态,那么父级控制选中与否的字段isChecked就应该是true
            if(this.acceptanceSelects) {
                this.acceptanceData.forEach(i => {
                    i.isChecked = true
                })
            } else {
                this.acceptanceData.forEach(i => {
                    i.isChecked = false
                })
            }
            // 点击全选的时候,把已经删除的子级changType设置为选中,如果某个父级下面所有的子级都为-1,则需要将这个父级的isChecked设置为true
            this.acceptanceData.forEach(item => {
                item.children.forEach(it => {
                    if(it.changeType === -1) {
                        this.$refs.acceptanceTable.toggleRowSelection(it, true)
                    }
                })
                let isCheckedAllChildren = item.children.every(its => its.changeType === -1)
                if(isCheckedAllChildren) {
                    this.$refs.acceptanceTable.toggleRowSelection(item, true)
                    item.isChecked = true
                }
            })
        },
        splite (data, flag) {
            data.forEach(row => {
                this.$refs.acceptanceTable.toggleRowSelection(row, flag)
                if(row.children != undefined) {
                    this.splite(row.children, flag)
                }
            })
        },
        // 当用户手动勾选数据行的 Checkbox 时触发的事件
        selectRow (selection, row) {
            if(row.children) {
                if(row.isChecked) {
                    row.children.forEach(item => {
                        if(item.changeType !== -1) {
                            this.$refs.acceptanceTable.toggleRowSelection(item, false)
                        }
                    })
                    row.isChecked = false
                } else {
                    row.children.forEach(item => {
                        if(item.changeType !== -1) {
                            this.$refs.acceptanceTable.toggleRowSelection(item, true)
                        }
                    })
                    row.isChecked = true
                }

            }else {
                const _parentId = row.parentId
                let count = 0
                const target = this.acceptanceData.find(i => {
                    if(i.topClassId === _parentId) {
                        i.children.forEach(its => {
                            if(its.changeType !== -1) {
                                count++
                            }
                        })
                        return i
                    }
                })

                const _target = selection.filter(it => {
                    return (it.parentId === _parentId) && (it.changeType !== -1)
                })
                if(count === _target.length) {
                    this.$refs.acceptanceTable.toggleRowSelection(target, true)
                    target.isChecked = true
                } else {
                    this.$refs.acceptanceTable.toggleRowSelection(target, false)
                    target.isChecked = false
                }
            }

            // // 全选判断
            const isAll = this.acceptanceData.every(i => {
                return i.isChecked === true
            })
            if(isAll) {
                this.tableHeadClass = 'tableHeadClass'
                this.acceptanceSelects = true
            } else {
                this.tableHeadClass = 'cancelClass'
                this.acceptanceSelects = false
            }
            // console.log(selection)
        },
        // 复选框选中的数据
        acceptanceSelect () {
            this.acceptanceList = this.$refs.acceptanceTable.selection
        },
        // 点击批量删除
        acceptanceDeleteClick () {
            this.acceptanceList = this.acceptanceList.filter(item => {
                if(item.children) {
                    const isEmpty = item.children.every(i => {
                        return i.changeType === -1
                    })
                    return isEmpty ? false : true
                } else {
                    return item.changeType !== -1
                }
            })
            const length = this.acceptanceList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.acceptanceDeleteList
                )
            }
        },
        // 批量删除
        acceptanceDeleteList () {
            this.acceptanceList.forEach(row => {
                if (row.dtlId) {
                    this.acceptanceData.forEach(item => {
                        const index = item.children.findIndex(
                            its => its.dtlId === row.dtlId
                        )
                        if(index !== -1) {
                            this.$set(item.children[index], 'changeType', -1)
                            this.$set(item.children[index], 'acceptanceAmount', 0)
                        }
                    })
                } else {
                    this.acceptanceData.forEach(item => {
                        item.children.forEach((its, index) => {
                            if (this._.isEqual(its, row)) {
                                item.children.splice(index, 1)
                            }
                        })
                    })
                }
            })
            this.$refs.acceptanceTable.clearSelection()
            let count = 0
            let countSum = 0
            this.acceptanceData.forEach(item => {
                count = +(item.children
                    .reduce((pre, c) => (pre += +c.acceptanceAmount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.formData.acceptanceAmount = +countSum.toFixed(2)
        },

        // ---------------------------------服务明细---------------------------------
        // 点击新增行
        serviceFeeAdd () {
            this.serviceFeeData.push({
                amount: '',
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: '',
                quantity: '',
                settlementUnitId: '',
                settlementUnitName: '',
                taxAmount: '',
                taxRate: '',
                totalAmount: ''
            })
        },

        // 获取服务费用表格数据(弹窗做好后,需要放开注释的)
        async getServeList () {
            let res = await priceRequest.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },

        // 结算单位弹窗选择点击保存后
        async billingUnitDialog (row, index) {
            // this.setSelectedInfo(this.jsdwData)
            // openAppClient('/showSelectedData', '选择结果')
            this.jsdwIds = row.settlementUnitId
            let res = await request.getBillingUnit(this.jsdwData, this.jsdwIds)
            let result = {
                amount: null,
                billId: this.billid,
                changeType: 1,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                contractQuantity: '',
                dtlId: '',
                invoiceNo: '',
                price: null,
                quantity: null,
                settlementUnitId: res.id,
                settlementUnitName: res.outerName,
                sourceServiceFeeDtlId: '',
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0
            }
            const shouldPush = this.serviceFeeData.every(
                it => it.settlementUnitId !== result.settlementUnitId
            )
            if (shouldPush) {
                this.serviceFeeData.splice(index, 1, result)
            } else {
                const repeatArr = this.serviceFeeData.filter(
                    i => i.settlementUnitId === result.settlementUnitId
                )
                const noPush = repeatArr.some(_its => _its.changeType !== -1)
                if (!noPush) {
                    this.serviceFeeData.splice(index, 1, result)
                }
            }
            this.formData.freight = +(this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.totalAmount || 0),
                0
            )).toFixed(2)
        },

        // 合同选择弹窗
        //  选择合同的接口由胡腾提供,合同的数据是从 物资采购合同服务清单,物流运输类服务采购合同清单
        async contractDialog (row, index) {
            let contracted = {
                contractId: row.contractBillId,
                contractType: row.contractBillType || 0
            }
            let res = await request.getContract(
                { orgid: this.orgId, contractId: this.formData.sourceBillId, contractType: '1' },
                contracted
            )
            // this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '选择结果')
            let result
            // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
            if (res.list && res.list.length > 0) {
                result = res.list.map(item => {
                    return {
                        amount: null,
                        billId: this.billid,
                        changeType: 1,
                        contractBillId: res.contractId,
                        contractBillNo: res.contractNumber,
                        contractDtlId: item.detailedId,
                        contractDtlName: item.name,
                        contractQuantity: item.quantity, // 这个字段是用于在修改数量时,不能大于合同数量的
                        dtlId: '',
                        invoiceNo: '',
                        price: null,
                        quantity: item.quantity,
                        settlementUnitId: res.secondPartyId,
                        settlementUnitName: res.secondPartyName,
                        sourceServiceFeeDtlId: '',
                        taxAmount: 0,
                        taxRate: res.taxRate,
                        totalAmount: 0
                    }
                })
                let _arr = []
                result.forEach(item => {
                    const shouldPush = this.serviceFeeData.every(
                        it => item.contractDtlId !== it.contractDtlId
                    )
                    if (shouldPush) {
                        _arr.push(item)
                    } else {
                        // 找到了清单ID相同
                        const repeatArr = this.serviceFeeData.filter(
                            i => item.contractDtlId === i.contractDtlId
                        )
                        const noPush = repeatArr.some(
                            _its => _its.changeType !== -1
                        )
                        if (!noPush) {
                            _arr.push(item)
                        }
                    }
                })
                if (_arr.length !== 0) {
                    this.serviceFeeData.splice(index, 1, ..._arr)
                }
            } else {
                // 如果选择的合同没有清单
                result = {
                    amount: null,
                    billId: this.billid,
                    changeType: 1,
                    contractBillId: res.contractId,
                    contractBillNo: res.contractNumber,
                    contractDtlId: '',
                    contractDtlName: '',
                    contractQuantity: '',
                    dtlId: '',
                    invoiceNo: '',
                    price: null,
                    quantity: null,
                    settlementUnitId: res.secondPartyId,
                    settlementUnitName: res.secondPartyName,
                    sourceServiceFeeDtlId: '',
                    taxAmount: 0,
                    taxRate: res.taxRate,
                    totalAmount: 0
                }
                const shouldPush = this.serviceFeeData.every(
                    it => it.contractBillId !== result.contractBillId
                )
                if (shouldPush) {
                    this.serviceFeeData.splice(index, 1, result)
                } else {
                    const repeatArr = this.serviceFeeData.filter(
                        i => i.contractBillId === result.contractBillId
                    )
                    const noPush = repeatArr.some(
                        _its => _its.changeType !== -1
                    )
                    if (!noPush) {
                        this.serviceFeeData.splice(index, 1, result)
                    }
                }
            }
            this.formData.freight = +(this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.totalAmount || 0),
                0
            )).toFixed(2)
        },
        // 清单名称
        contractDtlNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },

        // 数量变化时
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 不能超过合同数量
            if (+row.contractQuantity) {
                if (+row.quantity > +row.contractQuantity) {
                    this.clientPop(
                        'err',
                        `不能大于合同数量${row.contractQuantity}`
                    )
                    row.quantity = row.contractQuantity
                }
            }
            if (+row.amount && +row.quantity) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            } else {
                row.price = 0
            }
        },
        // 金额变化时
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.quantity) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            }else{
                row.price = 0
            }
            if (+row.amount && +row.taxRate) {
                row.taxAmount = +(+row.amount * (+row.taxRate / 100)).toFixed(2)
            }else{
                row.taxAmount = 0
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            }else{
                row.totalAmount = 0
            }
            this.formData.freight = +(this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.totalAmount || 0),
                0
            )).toFixed(2)
        },
        // 编号变化时
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 税率变化时
        taxRateBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.taxRate) {
                row.taxAmount = +(+row.amount * (+row.taxRate / 100)).toFixed(2)
            }else {
                row.taxAmount = 0
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            }else{
                row.totalAmount = 0
            }
        },
        //税额变化时
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            }else {
                row.totalAmount = 0
            }
        },

        // 服务费用单条删除
        serviceFeeDelete (row, index) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.dtlId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.serviceFeeData.splice(index, 1)
                }
                row.amount = 0
                row.totalAmount = 0
                this.formData.freight = +(this.serviceFeeData.reduce(
                    (pre, c) => (pre += +c.totalAmount || 0),
                    0
                )).toFixed(2)
            })
        },
        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // 复选框选中的数据
        serviceFeeSelect (selection) {
            this.serviceFeeList = selection.filter(
                item => item.changeType !== -1
            )
        },
        // 点击批量删除
        serviceFeeDeleteClick () {
            const length = this.serviceFeeList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.serviceFeeDeleteList
                )
            }
        },
        // 批量删除
        serviceFeeDeleteList () {
            this.serviceFeeList.forEach(row => {
                if (row.dtlId) {
                    const index = this.serviceFeeData.findIndex(item => {
                        return item.dtlId == row.dtlId
                    })
                    this.$set(this.serviceFeeData[index], 'changeType', -1)
                    this.$set(this.serviceFeeData[index], 'amount', 0)
                    this.$set(this.serviceFeeData[index], 'totalAmount', 0)
                } else {
                    this.serviceFeeData.forEach((item, index) => {
                        if (this._.isEqual(item, row)) {
                            this.serviceFeeData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.serviceFeeTable.clearSelection()
            this.formData.freight = +(this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.totalAmount || 0),
                0
            )).toFixed(2)
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置验收明细有错误时在表格上面显示的错误信息
        setErrorAcceptanceMsg (msg) {
            let index = this.errorAcceptanceMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorAcceptanceMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks = this.formData.remarks
                        }
                        priceRequest
                            .basicInfoSave(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存验收明细时需要检测的
        saveAcceptance () {
            this.errorAcceptanceMsg = []
            return new Promise((resolve, reject) => {
                if (this.isSubmit) {
                    // 如果点击的是提交审核才需要判断验收明细是否为空,为空时不能提交审核
                    if (this.acceptanceData.length < 1) {
                        this.setErrorAcceptanceMsg('请选择需验收的数据')
                        this.setError('receivingMaterials')
                        reject('验收明细错误')
                        return
                    } else {
                        // 如果每一个子项的changeType都为 -1  就说明都删除了, 那就不能提交审核
                        let arr = []
                        this.acceptanceData.forEach(item => {
                            let isData = item.children.every(
                                its => its.changeType === -1
                            )
                            arr.push(isData)
                        })
                        let isSubmit = arr.every(i => i === true)
                        if (isSubmit) {
                            this.setErrorAcceptanceMsg('请选择需验收的数据')
                            this.setError('receivingMaterials')
                            reject('验收明细错误')
                            return
                        }
                    }
                }
                this.acceptanceData.forEach(its => {
                    its.children.forEach(item => {
                        if (item.changeType !== -1) {
                            !item.materialClassName
                                ? this.setErrorAcceptanceMsg('请填写物资类别')
                                : ''
                            !item.materialName
                                ? this.setErrorAcceptanceMsg('请填写物资名称')
                                : ''
                            !item.unit
                                ? this.setErrorAcceptanceMsg('请填写计量单位')
                                : ''
                            !item.warehouseName
                                ? this.setErrorAcceptanceMsg('请填写仓库')
                                : ''
                            !item.notAcceptedQuantity
                                ? this.setErrorAcceptanceMsg('请填写未验收数量')
                                : ''
                            !item.acceptanceQuantity
                                ? this.setErrorAcceptanceMsg('请填写验收数量')
                                : ''
                            item.price === '' || item.price === null || isNaN(item.price)
                                ? this.setErrorAcceptanceMsg(
                                    '请填写验收单价(元)'
                                )
                                : ''
                            item.acceptanceAmount === '' || item.acceptanceAmount === null || isNaN(item.acceptanceAmount)
                                ? this.setErrorAcceptanceMsg(
                                    '请填写验收金额(元)'
                                )
                                : ''
                        }
                    })
                })
                if (this.errorAcceptanceMsg.length > 0) {
                    this.setError('receivingMaterials')
                    reject('验收明细错误')
                    return
                } else {
                    this.acceptanceData.push(...this.acceptanceDelData)
                    priceRequest
                        .saveAcceptance(this.acceptanceData)
                        .then(() => {
                            this.getAcceptanceList()
                            this.clearError('receivingMaterials')
                            resolve()
                        })
                        .catch(err => {
                            this.errorAcceptanceMsg[0] = err.message
                            this.setError('receivingMaterials')
                            reject(err)
                        })
                }
            })
        },
        // 保存服务明细时需要检测的
        saveServiceFee () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    if (item.changeType !== -1) {
                        !item.settlementUnitName
                            ? this.setErrorServiceFeeMsg('请填写结算单位')
                            : ''
                        !item.contractDtlName
                            ? this.setErrorServiceFeeMsg('请填写清单名称')
                            : ''
                        !item.quantity
                            ? this.setErrorServiceFeeMsg('请填写数量')
                            : ''
                        item.price === '' || item.price === null || isNaN(item.price)
                            ? this.setErrorServiceFeeMsg('请填写单价(元)')
                            : ''
                        item.amount === '' || item.amount === null || isNaN(item.amount)
                            ? this.setErrorServiceFeeMsg('请填写金额(元)')
                            : ''
                        item.totalAmount === '' || item.totalAmount === null || isNaN(item.totalAmount)
                            ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                            : ''
                    }
                })
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('serviceCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    priceRequest
                        .saveServiceFee(this.serviceFeeData)
                        .then(() => {
                            this.getServeList()
                            this.clearError('serviceCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('serviceCharge')
                            reject(err)
                        })
                }
            })
        },
        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            // 汇总验收数量
            let count = 0
            let countSum = 0
            this.acceptanceData.forEach(item => {
                count = +(item.children
                    .reduce((pre, c) => (pre += +c.acceptanceQuantity || 0), 0))
                    .toFixed(4)
                countSum += +count
                // 计算每一行的税额
                item.children.forEach(it => {
                    it.taxAmount = +Number(+it.acceptanceAmount * (+this.formData.taxRate / 100)).toFixed(2)
                })
            })
            this.formData.acceptanceQuantity = +countSum.toFixed(4)
            Promise.all([
                this.updateBaseInfo(),
                this.saveAcceptance(),
                this.saveServiceFee()
            ])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },

        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            // 汇总验收数量
            let count = 0
            let countSum = 0
            this.acceptanceData.forEach(item => {
                count = +(item.children
                    .reduce((pre, c) => (pre += +c.acceptanceQuantity || 0), 0))
                    .toFixed(4)
                countSum += +count
                // 计算每一行的税额
                item.children.forEach(it => {
                    it.taxAmount = +Number(+it.acceptanceAmount * (+this.formData.taxRate / 100)).toFixed(2)
                })
            })
            this.formData.acceptanceQuantity = +countSum.toFixed(4)
            Promise.all([
                this.updateBaseInfo(),
                this.saveAcceptance(),
                this.saveServiceFee()
            ])
                .then(() => {
                    // 需要验证基本信息中税价合计和服务费用两者不能同时为0
                    if(this.formData.totalAmount == 0 && this.formData.freight == 0) {
                        this.clientPop('err', '税价合计和服务费用，两者不可同时为0。')
                        return
                    }
                    request
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            // this.clientPop('err', '提交失败', () => {
                            this.scorllError()
                            // })
                        })
                })
                .catch(() => {
                    this.clientPop('err', '提交失败', () => {
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            showLoading()
            request
                .undoAudit(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        deleteData () {
            this.clientPop('info', this.oneDeleteErr, () => {
                showLoading()
                priceRequest
                    .basicInfoDelete(this.billid)
                    .then(() => {
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.isSubmit = false
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.isSubmit = true
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.deleteData() // 删除
            }
        },

        // ------------------------上面小刘---------

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon')) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/priceCheck')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.value
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
.tableHeadClass {
        ::v-deep .el-checkbox__inner{
            background: #2f62d7 !important;
        }
}
.cancelClass {
        ::v-deep .el-checkbox__inner {
        background: #fff !important;
        }
}
</style>
